
/*
 * VytvoreniProjektu.java
 *
 * Created on Nov 22, 2011, 11:47:48 AM
 */
package gui;

import database.DatabazovaChyba;
import gui.comboBoxRenderers.StavComboBoxRenderer;
import gui.comboBoxRenderers.VlastnikComboBoxRenderer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import system.Launcher;
import ukoly.ProjektControl;
import ukoly.UkolStatus;
import uzivatele.Uzivatel;
import uzivatele.UzivatelRank;

/**
 *
 * @author Jan Lukes, Pavel Lieberzeit
 */
public class VytvoreniProjektu extends javax.swing.JFrame {

    private ProjektControl projekt;

    /** Creates new form VytvoreniProjektu 
     * @param projekt Projekt, ktery se edituje nebo null (kdyz se vytvari novy)
     */
    public VytvoreniProjektu(ProjektControl projekt) {
        this.projekt = projekt;
        initComponents();
        String nazevOkna = "Editace projektu";
        if (projekt == null) {
            nazevOkna = "Vytvoření projektu";
        }
        this.setTitle("Správce úkolů - " + nazevOkna
                + " - Přihlášen " + Launcher.getInstance().getUzivatel().getEmail()
                + " - " + UzivatelRank.getNameFromRankId(Launcher.getInstance().getUzivatel().getRank()));
        Launcher.getInstance().setOknoDoprostred(this);
//        Uzivatel uzivatel = Launcher.getInstance().getUzivatel();
//        String pravaUzivatele = UzivatelRank.getNameFromRankId(uzivatel.getRank());
//        String jmeno = uzivatel.getJmeno();
//        this.setTitle(jmeno + " (" + pravaUzivatele + ")");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        Uzivatel uzivatel = Launcher.getInstance().getUzivatel(); //cache, trochu to zrychly celou inicializaci
        nazevLabel = new javax.swing.JLabel();
        nazevTextField = new javax.swing.JTextField();
        popisLabel = new javax.swing.JLabel();
        popisScrollPane = new javax.swing.JScrollPane();
        popisTextArea = new javax.swing.JTextArea();
        dateCreateLabel = new javax.swing.JLabel();
        dateCreateTextField = new javax.swing.JTextField();
        dateEndLabel = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        dateFinishTextField = new javax.swing.JTextField();
        dateDeadTextField = new javax.swing.JTextField();
        dateDeadLabel = new javax.swing.JLabel();
        casStravenLabel = new javax.swing.JLabel();
        casStravenTextField = new javax.swing.JTextField();
        stavComboBox = new javax.swing.JComboBox();
        stavLabel = new javax.swing.JLabel();
        odpovednyLabel = new javax.swing.JLabel();
        odpovednyComboBox = new javax.swing.JComboBox();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        nazevLabel.setText("Název:");

        if(this.projekt == null) {
            nazevTextField.setText("");
        } else {
            nazevTextField.setText(this.projekt.getModel().getJmeno());
        }
        nazevTextField.setDisabledTextColor(GUIConstants.DISABLED_TEXT_COLOR);
        if(uzivatel.getRank() == 0)
        nazevTextField.setEnabled(false);

        popisLabel.setText("Popis:");

        popisTextArea.setColumns(20);
        popisTextArea.setLineWrap(true);
        popisTextArea.setRows(5);
        popisTextArea.setWrapStyleWord(true);
        popisTextArea.setDisabledTextColor(GUIConstants.DISABLED_TEXT_COLOR);
        if(this.projekt == null) {
            popisTextArea.setText("");
        } else {
            popisTextArea.setText(this.projekt.getModel().getPopis());
        }

        if(uzivatel.getRank() == 0)
        popisTextArea.setEnabled(false);
        popisScrollPane.setViewportView(popisTextArea);

        dateCreateLabel.setText("Vytvoření:");

        dateCreateTextField.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        dateCreateTextField.setDisabledTextColor(GUIConstants.DISABLED_TEXT_COLOR);
        dateCreateTextField.setEnabled(false);
        if(this.projekt == null) {
            GregorianCalendar time = new GregorianCalendar();
            time.setTime(new Date(System.currentTimeMillis()));
            dateCreateTextField.setText(time.get(Calendar.DAY_OF_MONTH)+"." + (int)(time.get(Calendar.MONTH)+1)
                +"." + time.get(Calendar.YEAR));
        } else {
            GregorianCalendar time = this.projekt.getModel().getCasStart();
            dateCreateTextField.setText(time.get(Calendar.DAY_OF_MONTH)+"." + (int)(time.get(Calendar.MONTH)+1)
                +"." + time.get(Calendar.YEAR));
        }

        dateEndLabel.setText("Ukončení:");

        saveButton.setText("Uložit");
        if(uzivatel.getRank() == 0)
        saveButton.setEnabled(false);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        deleteButton.setText("Smazat");
        if(uzivatel.getRank() == 0 || this.projekt == null)
        deleteButton.setEnabled(false);
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        dateFinishTextField.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        dateFinishTextField.setDisabledTextColor(GUIConstants.DISABLED_TEXT_COLOR);
        dateFinishTextField.setEnabled(false);
        if(this.projekt == null || this.projekt.getModel().getCasKonec() == null) {
            dateFinishTextField.setText("");
        } else {
            GregorianCalendar time = this.projekt.getModel().getCasKonec();
            dateFinishTextField.setText(time.get(Calendar.DAY_OF_MONTH) + "." + (int)(time.get(Calendar.MONTH)+1)
                + "." + time.get(Calendar.YEAR));
        }

        dateDeadTextField.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        dateDeadTextField.setDisabledTextColor(GUIConstants.DISABLED_TEXT_COLOR);
        if(this.projekt == null || this.projekt.getModel().getCasDead() == null) {
            dateDeadTextField.setText("");
        } else {
            GregorianCalendar time = this.projekt.getModel().getCasDead();
            dateDeadTextField.setText(time.get(Calendar.DAY_OF_MONTH) + "." + (int)(time.get(Calendar.MONTH)+1)
                + "." + time.get(Calendar.YEAR));
        }

        if(uzivatel.getRank() == 0)
        dateDeadTextField.setEnabled(false);

        dateDeadLabel.setText("Deadline:");

        casStravenLabel.setText("Čas stráven:");

        if(this.projekt == null)
        casStravenTextField.setText("0");
        else
        casStravenTextField.setText(Integer.toString(this.projekt.getModel().getCasStraven()));

        if(uzivatel.getRank() == 0) //TODO pridelat opravneni jen pro managera, co to spravuje
        casStravenTextField.setEnabled(false);
        casStravenTextField.setHorizontalAlignment(javax.swing.JTextField.TRAILING);
        casStravenTextField.setDisabledTextColor(GUIConstants.DISABLED_TEXT_COLOR);

        stavComboBox.setModel(new javax.swing.DefaultComboBoxModel(UkolStatus./*stavy/*/values()));
        stavComboBox.setRenderer(new StavComboBoxRenderer());
        if(this.projekt == null || this.projekt.getModel().getStatus() == null) {
            stavComboBox.setSelectedItem(UkolStatus.NEW);
        } else {
            stavComboBox.setSelectedItem(this.projekt.getModel().getStatus());
        }

        if(uzivatel.getRank() == 0)
        stavComboBox.setEnabled(false);

        stavLabel.setText("Stav:");

        odpovednyLabel.setText("Odpovědný:");

        ArrayList <Uzivatel> uzivatele = null;

        try{
            uzivatele = Launcher.getInstance().getDatabase().vyberUzivatele("WHERE rank>'0'");
        }catch(DatabazovaChyba ex) {
            JOptionPane.showMessageDialog(this.getFocusOwner(), "Chyba v komunikaci s databází\n"+ex.getMessage());
        }

        DefaultComboBoxModel vlastnikModel = new DefaultComboBoxModel();
        //vlastnikModel.addElement(null);
        for(Uzivatel u : uzivatele) {
            vlastnikModel.addElement(u);
        }
        odpovednyComboBox.setModel(vlastnikModel/*new javax.swing.DefaultComboBoxModel(moznosti//new String[] { "Jan Novák", "Josef Velký" })*/);
        odpovednyComboBox.setRenderer(new VlastnikComboBoxRenderer());
        if(this.projekt == null || this.projekt.getModel().getOdpovedny() == null) {
            odpovednyComboBox.setSelectedIndex(0);
        } else {
            odpovednyComboBox.setSelectedItem(this.projekt.getModel().getOdpovedny());
        }

        if(uzivatel.getRank() == 0) {
            odpovednyComboBox.setEnabled(false);
        }

        cancelButton.setText("Zrušit");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(odpovednyLabel)
                    .addComponent(nazevLabel)
                    .addComponent(dateCreateLabel)
                    .addComponent(popisLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(nazevTextField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(dateCreateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dateEndLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dateFinishTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dateDeadLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(dateDeadTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(odpovednyComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(stavLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(stavComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(casStravenLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(casStravenTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(popisScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 537, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(43, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nazevLabel)
                    .addComponent(nazevTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dateCreateLabel)
                    .addComponent(dateCreateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dateEndLabel)
                    .addComponent(dateFinishTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dateDeadLabel)
                    .addComponent(dateDeadTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(odpovednyLabel)
                    .addComponent(odpovednyComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(stavLabel)
                    .addComponent(stavComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(casStravenLabel)
                    .addComponent(casStravenTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(popisLabel)
                    .addComponent(popisScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(deleteButton)
                    .addComponent(cancelButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

        boolean error = false;
//        System.out.println(popisTextArea.getText());

        GUIConstants.odznacChybu(dateDeadTextField);
        if (GUIConstants.checkDeadline(this.dateDeadTextField.getText())) {
            GUIConstants.ukazChybu(dateDeadTextField);
            error = true;
        }
        
        GUIConstants.odznacChybu(nazevTextField);
        if(nazevTextField.getText().isEmpty()) {
            GUIConstants.ukazChybu(nazevTextField);
            error = true;
        }

        GUIConstants.odznacChybu(casStravenTextField);
        if (GUIConstants.checkCasStraven(this.casStravenTextField.getText())) {
            GUIConstants.ukazChybu(casStravenTextField);
            error = true;
        }

        if (error) {
            return;
        }


        if (this.projekt == null) {
            try {

                ProjektControl.createProjekt(-1, nazevTextField.getText(), popisTextArea.getText(), GUIConstants.preprocDeadline(this.dateDeadTextField.getText()),
                        (Uzivatel) odpovednyComboBox.getSelectedItem(), (UkolStatus) stavComboBox.getSelectedItem(), Integer.parseInt(casStravenTextField.getText()));

            } catch (DatabazovaChyba ex) {
                JOptionPane.showMessageDialog(this.getFocusOwner(), "Chyba v komunikaci s databází\n" + ex.getMessage());
            }
        } else {
            try {
                this.projekt.editProjekt(nazevTextField.getText(), popisTextArea.getText(),
                        GUIConstants.preprocDeadline(this.dateDeadTextField.getText()), (Uzivatel) odpovednyComboBox.getSelectedItem(),
                        (UkolStatus) stavComboBox.getSelectedItem(), Integer.parseInt(casStravenTextField.getText()));
            } catch (DatabazovaChyba ex) {
                JOptionPane.showMessageDialog(this.getFocusOwner(), "Chyba v komunikaci s databází\n" + ex.getMessage());
            }
        }
        Launcher.getInstance().refresh();

        this.dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        
        int n = JOptionPane.showConfirmDialog(
                this,
                "Opravdu chcete smazat vybraný projekt?\n"
                + "Tuto akci nelze vrátit!",
                "Potvrzení",
                JOptionPane.YES_NO_OPTION);

        if (n == /*0 */JOptionPane.YES_OPTION) {
        
            try {
                this.projekt.deleteProjekt();
            } catch (DatabazovaChyba ex) {
                JOptionPane.showMessageDialog(this.getFocusOwner(), "Chyba v komunikaci s databází\n" + ex.getMessage());
            }

            Launcher.getInstance().refresh();
            JOptionPane.showMessageDialog(this, "Projekt smazán.");
            this.dispose();
        }
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel casStravenLabel;
    private javax.swing.JTextField casStravenTextField;
    private javax.swing.JLabel dateCreateLabel;
    private javax.swing.JTextField dateCreateTextField;
    private javax.swing.JLabel dateDeadLabel;
    private javax.swing.JTextField dateDeadTextField;
    private javax.swing.JLabel dateEndLabel;
    private javax.swing.JTextField dateFinishTextField;
    private javax.swing.JButton deleteButton;
    private javax.swing.JLabel nazevLabel;
    private javax.swing.JTextField nazevTextField;
    private javax.swing.JComboBox odpovednyComboBox;
    private javax.swing.JLabel odpovednyLabel;
    private javax.swing.JLabel popisLabel;
    private javax.swing.JScrollPane popisScrollPane;
    private javax.swing.JTextArea popisTextArea;
    private javax.swing.JButton saveButton;
    private javax.swing.JComboBox stavComboBox;
    private javax.swing.JLabel stavLabel;
    // End of variables declaration//GEN-END:variables
}
